import { prisma } from '@/lib/db'

const getTeam = async (slug: string) => {
  return prisma.team.findFirst({
    where: {
      slug,
    },
  })
}

const createTeam = async (userId: any, payload: any) => {
  return prisma.$transaction(async (tx) => {
    const newTeam = await tx.team.create({
      data: {
        ...payload,
        createdBy: {
          connect: {
            id: userId,
          },
        },
        teamMembers: {
          create: {
            user: {
              connect: {
                id: userId,
              },
            },
            role: 'OWNER',
          },
        },
      },
    })
    await tx.user.update({
      where: { id: userId },
      data: {
        currentTeamSlug: newTeam.slug,
      },
    })
    return newTeam
  })
}

const getAllTeams = async (userId: any) => {
  return prisma.team.findMany({
    where: {
      OR: [
        { createdById: userId }, // 查询用户创建的团队，假设字段为createdById
        { teamMembers: { some: { userId } } }, // 查询用户作为成员的团队
      ],
    },
  })
}

export { getTeam, createTeam, getAllTeams }
